from rest_framework import viewsets
from rest_framework.decorators import action
from rest_framework.pagination import PageNumberPagination
from rest_framework.response import Response
from rest_framework.status import HTTP_400_BAD_REQUEST

from MirrorCore.models.Badge import Badge, ArticleBadge, EssayBadge
from MirrorCore.permissions.permisssion import IsStaffOrReadOnly
from MirrorCore.serializers.ArticleSerializer import ArticleSerializer

from MirrorCore.serializers.BadgeSeriralizer import BadgeSerializer, ArticleBadgeSerializer
from MirrorCore.serializers.EssaySerializer import EssaySerializer
from MirrorCore.views.utils.Pagination import GetByPagination


class BadgeResultsSetPagination(PageNumberPagination):
    page_size = 10000

class BadgeViewSet(viewsets.ModelViewSet):
    serializer_class = BadgeSerializer
    pagination_class = BadgeResultsSetPagination

    permission_classes = [IsStaffOrReadOnly]


    def get_queryset(self):
        """
            TODO: 并没有限制衍生badge在文章中呈现，
        :return:
        """
        if self.request.user.is_staff:
            return Badge.objects.all().order_by("-id")
        return Badge.objects.filter(is_active=True).order_by("-id")

    @action(detail=True,methods=['get'])
    def get_content(self,request,pk=None):
        """
        获得标签对应的文章内容
        :param request: type 请求内容列表 (article, default=essay)
        :param pk: badgeid
        :return:
        """

        type = request.GET.get('type', default='essay')
        page = request.GET.get('page',default='1')
        # 总数
        count = 0
        ret = []
        filter1 = {'badge': pk}
        if self.request.user.is_staff is not True:
            filter1['%s__is_active' % type] = True

        # TODO: 每篇文章请求作者时，产生重复数据库请求
        if type == 'article':
            list = ArticleBadge.objects.select_related('article').filter(**filter1).order_by('-id')
            pglist, count = GetByPagination(list,10,page)
            for badge in pglist:
                ret.append(badge.article)
            ser = ArticleSerializer(ret,many=True)

        elif type == 'essay':
            list = EssayBadge.objects.select_related('essay').filter(**filter1).order_by('-id')
            pglist,count = GetByPagination(list, 10, page)
            for badge in pglist:
                ret.append(badge.essay)
            ser = EssaySerializer(ret, many=True)

        else:
            return Response({
                'type': "type不正确"
            }, status=HTTP_400_BAD_REQUEST)

        return Response({
            "count": count,
            "results": ser.data
        })

    def create(self, request, *args, **kwargs):
        return super().create(request, *args, **kwargs)

    def update(self, request, *args, **kwargs):

        return super().update(request, *args, **kwargs)


class ArticleBadgeViewSet(viewsets.ModelViewSet):
    queryset = ArticleBadge.objects.all()
    serializer_class = ArticleBadgeSerializer
    permission_classes = [IsStaffOrReadOnly]
